#include <iostream>
#include <opencv2/opencv.hpp>


using namespace std;
using namespace cv;


int main(int argc, char **argv) {

    Mat src = Mat(400.,400, CV_8UC3,Scalar(0,0,0));

    Vec4f lines;
    vector<Point2f> points;
    const static float pts[20][2] = {
            {0.0f,0.0f},{10.0f,11.0f},{21.0f,20.0f},{30.0f,30.0f},
            {40.0f,42.0f},{50.0f,50.0f},{60.0f,60.0f},{70.0f,70.0f},
            {80.0f,80.0f},{90.0f,92.0f},{100.0f,100.0f},{110.0f,110.0f},
            {120.f,120.0f},{136.0f,130.0f},{138.0f,140.0f},{150.0f,150.0f},
            {160.0f,163.0f},{175.0f,170.0f},{181.0f,180.0f},{200.0f,190.0f}
    };

    for (int i = 0; i < 20; ++i) {
        points.emplace_back(pts[i][0], pts[i][1]);
        circle(src, Point(pts[i][0], pts[i][1]), 3, Scalar(255, 255, 255));
    }

    double param = 0.0;
    double reps = 0.01;
    double aeps = 0.01;
    fitLine(points, lines, DIST_L1, param, reps, aeps);
    
    // output[0],output[1]是一个方向向量，output[2],output[3]是直线上一个点
    double k = lines[1] / lines[0];
    double b = lines[3] - k * lines[2];

    cout << "lines:  " << lines << "\n  y = " << k << "x + " << b << endl;

    Point Point_start;
    Point Point_end;
    Point_start.x = 0;
    Point_start.y = b;
    Point_end.x = 200;
    Point_end.y = k * 200 + b;

    
    line(src,Point_start, Point_end,Scalar(255,255,255),1);

    imshow("src1", src);
    waitKey(0);

    return 0;
}

